package org.example.util.file;

import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther admin闫
 * @Descriptopn 解压RAR文件
 * @date 2024/4/5 0:55
 */
public class RARUtil {

    /**
     * 解压RAR文件到指定目标路径
     * @param rarFilePath RAR文件路径
     * @param destination 解压到的目标路径
     * @throws IOException 如果发生IO异常
     * @throws RarException 如果RAR文件格式有误
     */
    public static void extractRar(String rarFilePath, String destination) throws IOException, RarException {
        File destinationDir = new File(destination);
        if (!destinationDir.exists()) {
            destinationDir.mkdirs();
        }
        Archive archive = new Archive(new File(rarFilePath));
        List<FileHeader> fileHeaders = new ArrayList<>();
        while (true) {
            FileHeader fileHeader = archive.nextFileHeader();
            if (fileHeader == null) {
                break;
            }
            fileHeaders.add(fileHeader);
        }
        for (FileHeader fileHeader : fileHeaders) {
            String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
            String destinationFilePath = destination + File.separator + fileName;
            File destinationFile = new File(destinationFilePath);
            if (fileHeader.isDirectory()) {
                destinationFile.mkdirs();
            } else {
                try (OutputStream outputStream = new FileOutputStream(destinationFile)) {
                    archive.extractFile(fileHeader, outputStream);
                }
            }
        }
    }
}
